package com.yiren.dbaa.module.practice_set.site.presenter;

import android.app.Activity;

import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.StationParamConfigBean;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.currency.constant.DbConstant;
import com.yiren.backstage.currency.entity.LineInfoEntity;
import com.yiren.backstage.currency.entity.MapEntity;
import com.yiren.backstage.currency.entity.SiteEntity;
import com.yiren.backstage.currency.utils.FileUtil;
import com.yiren.backstage.db.dao.controller.GradeDbController;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.constant.AddressConstant;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.currency.event.FragmentRefreshEvent;
import com.yiren.dbaa.module.param_config.api.ParamConfigApi;
import com.yiren.dbaa.module.practice_set.line.contract.LineHomeContract;
import com.yiren.dbaa.module.practice_set.line.model.LineHomeModel;
import com.yiren.dbaa.module.practice_set.map.contract.MapHomeContract;
import com.yiren.dbaa.module.practice_set.map.model.MapHomeModel;
import com.yiren.dbaa.module.practice_set.site.bean.BaseRuleNewBean;
import com.yiren.dbaa.module.practice_set.site.bean.LineDataValBean;
import com.yiren.dbaa.module.practice_set.site.bean.ModifyValBean;
import com.yiren.dbaa.module.practice_set.site.contract.SiteRuleContract;
import com.yiren.dbaa.module.practice_set.site.model.SiteRuleModel;
import com.yiren.dbaa.view.dialog.LoadDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

/**
 * @author lwb
 * @date : 2022/9/20 14:40
 * @description: 考场规则presenter
 */
public class SiteRulePresenter implements SiteRuleContract.Presenter {

    private Activity activity;
    private SiteRuleContract.Model siteRuleModel;
    private LineHomeContract.Model lineHomeModel;
    private MapHomeContract.Model mapHomeModel;
    private UserParamConfigBean userParamConfig;

    /*** 合伙人服务器已公开考规列表 便于更新模板使用 */
    private List<SiteEntity> partneSites;

    public SiteRulePresenter(Activity activity) {
        this.activity = activity;
        siteRuleModel = new SiteRuleModel(activity);
        userParamConfig = LoadConfigApi.loadUserParamConfig(activity);
        lineHomeModel = new LineHomeModel(activity);
        mapHomeModel = new MapHomeModel(activity);
    }

    @Override
    public void loadSiteRuleList(SiteRuleContract.View view) {
        //从服务器获取考规列表 合伙人获取自己已发布考规，教练获取所属合伙人已发布考规
        LoadDialog.show(activity, "正在加载...");
        siteRuleModel.getSiteRuleFromServer(userParamConfig.getUserInfo().getpUserId().toString(), false, new CommonCallBack() {
            @Override
            public void success(Object result) {
                LoadDialog.dismiss(activity);
                List<SiteEntity> serverSites = (List<SiteEntity>) result;
                partneSites = serverSites;
                //获取本地考规列表
                List<SiteEntity> localSites = UserDbController.getInstance(false).queryAll(SiteEntity.class);
                for (SiteEntity site:localSites){
                    site.setDownLoad(true);
                }
                if (null == serverSites || serverSites.size() == 0) {
                    view.showSiteRuleList(localSites);
                    return;
                }
                if (null == localSites || localSites.size() == 0) {
                    view.showSiteRuleList(serverSites);
                    return;
                }
                //数据合并去重，服务器与本地数据都存在以本地数据为准
                siteRuleModel.getNewBaseRule(new CommonCallBack() {
                    @Override
                    public void success(Object result) {
                        List<BaseRuleNewBean> baseRuleNewBeanlist = (List<BaseRuleNewBean>) result;
                        if (baseRuleNewBeanlist.size() > 0)
                            view.showSiteRuleList(siteRuleModel.siteRuleHomedataMerge(baseRuleNewBeanlist.get(0), localSites, serverSites));
                    }
                });
            }

            @Override
            public void fail(String error) {
                LoadDialog.dismiss(activity);
                MessageBox.show(activity, error);
                //获取失败加载本地
                List<SiteEntity> localSites = UserDbController.getInstance(false).queryAll(SiteEntity.class);
                UserParamConfigBean userParamConfigBean = LoadConfigApi.loadUserParamConfig(activity);
                for (SiteEntity localSite : localSites) {
                    //判断本地文件是否存在
                    if (FileUtil.exists(DbConstant.App_Main_Directory + userParamConfigBean.getUserInfo().getId() + "/my/" + localSite.getSiteCode() + "/" + DbConstant.GRADE_DATA_NAME))
                        localSite.setDownLoad(true);
                }
                view.showSiteRuleList(localSites);
            }
        });
    }

    @Override
    public void downLoadSiteRuleData(SiteEntity siteEntity, SiteRuleContract.View view) {
        //下载基础模板数据
        siteRuleModel.downLoadBaseData(siteEntity, new CommonCallBack() {
            @Override
            public void success(Object result) {
                super.success(result);
                //下载修改数据
                siteRuleModel.downLoadModifyVal(userParamConfig.getUserInfo().getId(), siteEntity.getSiteCode(), siteEntity.getRuleVer(), new CommonCallBack() {
                    @Override
                    public void success(Object result) {
                        super.success(result);
                        //本地数据插入
                        ModifyValBean modifyValBean = (ModifyValBean) result;
                        siteEntity.setPartneModifyVal(modifyValBean.getPartneModifyVal());
                        siteEntity.setCoachModifyVal(modifyValBean.getCoachModifyVal());
                        if (UserDbController.getInstance(false).insertOrReplace(siteEntity)) {
                            //通知视图
                            userParamConfig.setSite(siteEntity);
                            ParamConfigApi.saveUserParamConfig(activity, userParamConfig);
                            DbConstant.GRADE_DATA_URL = DbConstant.App_Main_Directory + userParamConfig.getUserInfo().getId() + "/my/" + userParamConfig.getSite().getSiteCode() + "/" + DbConstant.GRADE_DATA_NAME;
                            GradeDbController.getInstance(true);
                            downloadLineInfoAndMap(siteEntity.getSiteCode());
                            EventBus.getDefault().post(new FragmentRefreshEvent());
                            view.refreshSiteRuleList();
                            MessageBox.MessageAndVoiceModel(activity, "下载成功");
                            LoadDialog.dismiss(activity);
                        } else {
                            MessageBox.MessageAndVoiceModel(activity, "下载失败");
                        }
                    }

                    @Override
                    public void fail(String error) {
                        super.fail(error);
                    }
                });
            }

            @Override
            public void fail(String error) {
                super.fail(error);
            }
        });
    }

    @Override
    public void updateSiteRule(SiteEntity site, SiteRuleContract.View view) {
        //获取当前考场合伙人最新信息
        for (SiteEntity partneSite : partneSites) {
            if (partneSite.getSiteCode().equals(site.getSiteCode())) {
                siteRuleModel.downLoadBaseData(partneSite, new CommonCallBack() {
                    @Override
                    public void success(Object result) {
                        siteRuleModel.downLoadModifyVal(userParamConfig.getUserInfo().getId(), partneSite.getSiteCode(), partneSite.getRuleVer(), new CommonCallBack() {
                            @Override
                            public void success(Object result) {
                                super.success(result);
                                //更新数据库
                                ModifyValBean modifyValBean = new ModifyValBean();
                                partneSite.setPartneModifyVal(modifyValBean.getPartneModifyVal());
                                partneSite.setCoachModifyVal(site.getCoachModifyVal());
                                partneSite.setRuleVer(site.getRuleVerLast());
                                partneSite.setUpdate(false);
                                UserDbController.getInstance(false).update(partneSite);
                                view.refreshSiteRuleList();
                                MessageBox.MessageAndVoiceModel(activity, "更新成功!");
                                //清除缓存
                            }

                            @Override
                            public void fail(String error) {
                                super.fail(error);
                            }
                        });
                    }

                    @Override
                    public void fail(String error) {
                        super.fail(error);
                    }
                });
                return;
            }
        }
    }

    @Override
    public void deleteSiteRule(SiteEntity site, CommonCallBack callBack) {
        UserParamConfigBean userParamConfigBean = LoadConfigApi.loadUserParamConfig(activity);
        //删除文件夹
        File file = new File(AddressConstant.App_Main_Directory() + userParamConfigBean.getUserInfo().getId() + "/my/" + site.getSiteCode());
        File to = new File(file.getAbsolutePath() + System.currentTimeMillis());
        file.renameTo(to);
        FileUtil.delFolder(to.getAbsolutePath());
        //清除本地记录
        if (UserDbController.getInstance(false).delete(site)) {
            callBack.success("");
        }
    }

    @Override
    public void downloadLineInfoAndMap(String siteCode) {
        int pUserID;
        int cUserID;
        if (userParamConfig.isPartner()) {
            pUserID = userParamConfig.getUserInfo().getId();
            cUserID = userParamConfig.getUserInfo().getId();
        } else {
            pUserID = userParamConfig.getUserInfo().getpUserId();
            cUserID = userParamConfig.getUserInfo().getId();
        }

        //加载线路
        siteRuleModel.getLineInfoBySiteCode(siteCode,pUserID, new CommonCallBack() {
            @Override
            public void success(Object result) {
                List<LineInfoEntity> lineInfoList = (List<LineInfoEntity>) result;
                for (LineInfoEntity lineInfo : lineInfoList) {
                    lineHomeModel.downLoadLinePointData(lineInfo.getName(), lineInfo.getLineVer(), siteCode, pUserID, cUserID, new CommonCallBack() {
                        @Override
                        public void success(Object result) {
                            //本地数据插入
                            LineDataValBean lineDataValBean = (LineDataValBean) result;
                            lineInfo.setPartneModifyVal(lineDataValBean.getPartnerLineData());
                            lineInfo.setCoachModifyVal(lineDataValBean.getCoachLineData());
                            GradeDbController.getInstance(false).insertOrReplace(lineInfo);
                            EventBus.getDefault().post(new FragmentRefreshEvent());
                        }
                    });
                }
            }
        });

        //加载地图
        siteRuleModel.getMapBySiteCode(siteCode,pUserID, new CommonCallBack() {
            @Override
            public void success(Object result) {
                List<MapEntity> mapList = (List<MapEntity>) result;
                for (MapEntity map : mapList) {
                    mapHomeModel.downloadSiteMap(siteCode, pUserID, map.getMapVer(), new CommonCallBack() {
                        @Override
                        public void success(Object result) {
                            UserDbController.getInstance(false).insertOrReplace(map);
                            EventBus.getDefault().post(new FragmentRefreshEvent());
                            if (userParamConfig.getSite().getSiteCode().equals(map.getSiteCode())) {
                                StationParamConfigBean stationParamConfig = LoadConfigApi.loadStationParamConfig(activity);
                                stationParamConfig.setBaseStationId(map.getBaseId());
                                ParamConfigApi.saveStationParamConfig(activity, stationParamConfig);
                            }
                        }
                    });
                }
            }
        });
    }

}